import React, { useEffect, useState } from 'react';
import { CommonStyle } from '../../../../../common/commonStyle.ts';
import Swiper from 'react-native-swiper';
import { Image, StyleSheet } from 'react-native';
import Tools from '../../../../../utils/Tools.ts';
import { Touchable } from 'react-native-toast-message/lib/src/components/Touchable';
import EventCollection from '../../eventCollection.ts';
import { updateBtnInformation } from '../../../../../redux/reducers/app.ts';
import { useDispatch } from 'react-redux';
import { AppDispatch } from '../../../../../redux/store.ts';

interface IBannerTemplateProps {
  data: IBtnFormatsList[];
}
const BannerTemplate: React.FC<IBannerTemplateProps> = (props) => {
  const [list, setList] = useState<IBtnFormatsList[]>([]);
  const [height, setHeight] = useState<number>(120);
  const dispatch = useDispatch<AppDispatch>();

  useEffect(() => {
    handleCalculateAltitude(0);
  }, [props.data]);

  /**
   * 计算图片高度
   * @param index
   */
  const handleCalculateAltitude = (index: number) => {
    const uri = props.data[index].value;
    Tools.calculateAltitude(uri)
      .then((res) => {
        setList(props.data);
        setHeight(res);
      })
      .then(() => {
        setList(props.data);
        setHeight(120);
      });
  };

  const handlePress = (item: IBtnFormatsList) => {
    EventCollection.onPress(item, 2);
    dispatch(updateBtnInformation({ ...item, moduleType: 2 }));
  };

  return (
    <React.Fragment>
      <Swiper removeClippedSubviews={true} loop={false} loadMinimal height={height} showsButtons={false} activeDotColor={CommonStyle.mainColor} paginationStyle={{ bottom: 10 }} onIndexChanged={handleCalculateAltitude}>
        {list.map((item, index) => {
          return (
            <Touchable key={index} onPress={() => handlePress(item)} onLongPress={() => EventCollection.onLongPress(item)} delayLongPress={500}>
              <Image source={{ uri: item.value }} height={height} resizeMode={'cover'} />
            </Touchable>
          );
        })}
      </Swiper>
    </React.Fragment>
  );
};
const styles = StyleSheet.create({
  silde: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#9DD6EB' },
});

export default BannerTemplate;
